package com.peace.hospital.feign.login.controller;


import com.alibaba.fastjson.JSON;
import com.peace.hospital.entity.common.ResponseBean;
import com.peace.hospital.entity.common.Staffinfo;
import com.peace.hospital.entity.system.Admin;
import com.peace.hospital.feign.config.JWTUtil;
import com.peace.hospital.feign.login.service.IRoleService;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录验证
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String userLogin(Admin admin) {
        Staffinfo roleAndUser = iRoleService.getAdminByuserName(admin.getAdminname());
  //      Subject subject = SecurityUtils.getSubject();//获取当前用户
 //       UsernamePasswordToken token = new UsernamePasswordToken(admin.getAdminname(), admin.getPassword());
//        try {
        //subject.login(token);
//            return  JSON.toJSONString(new ResponseBean(200, "Login success", JWTUtil.sign(admin.getAdminname(),admin.getPassword())));
//        }catch (Exception e) {
//            return  JSON.toJSONString(new ResponseBean(402, "Login fail（密码错误）"));
//        }
        System.out.println(DigestUtils.md5DigestAsHex(admin.getAdminname().getBytes()));
        if (roleAndUser != null)
            if (roleAndUser.getStapassword().equals(DigestUtils.md5DigestAsHex(admin.getAdminname().getBytes()))) {
                //获取redis中的数据集合
//                ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
//                valueOperations.set("userData",JSON.toJSONString(admin));
//                System.out.println(valueOperations.get("userData"));
                return JSON.toJSONString(new ResponseBean(200, "Login success", JWTUtil.sign(admin.getAdminname(),DigestUtils.md5DigestAsHex(admin.getAdminname().getBytes()))));
            } else {
                // throw new UnauthorizedException();
                return JSON.toJSONString(new ResponseBean(402, "Login fail（密码错误）"));
            }
        return JSON.toJSONString(new ResponseBean(403, "Login fail(无此账户)"));
    }


    /***
     * URL结构
     *
     * URL	作用
     * /login	登入
     * /article	所有人都可以访问，但是用户与游客看到的内容不同
     * /require_auth	登入的用户才可以进行访问
     * /require_role	admin的角色用户才可以登入
     * /require_permission	拥有view和edit权限的用户才可以访问
     */
    //注解默认所有角色都满足才能访问，添加logical = Logical.OR即可满足一种角色即可
    @GetMapping("/index")
    @RequiresAuthentication
    public String getIndexData(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        String username = JWTUtil.getUsername(header);
        return JSON.toJSONString(username);
    }

    @GetMapping("/article")
    public ResponseBean article() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return new ResponseBean(200, "You are already logged in", null);
        } else {
            return new ResponseBean(200, "You are guest", null);
        }
    }

    @GetMapping("/require_auth")
    @RequiresAuthentication//登录才能访问
    public ResponseBean requireAuth() {
        return new ResponseBean(200, "You are authenticated", null);
    }

    @GetMapping("/require_role")
    @RequiresRoles(value = {"system", "root"})//拥有admin角色才能访问
    public ResponseBean requireRole() {
        return new ResponseBean(200, "You are visiting require_role", null);
    }

    @GetMapping("/require_permission")
    @RequiresPermissions(logical = Logical.AND, value = {"view", "edit"})//拥有view,edit权限才能访问
    public ResponseBean requirePermission() {
        return new ResponseBean(200, "You are visiting permission require edit,view", null);
    }

    @RequestMapping(path = "/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)//异常页面
    public ResponseBean unauthorized() {
        return new ResponseBean(401, "Unauthorized", null);
    }
}
